﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using SmartMD.DataModel.Entity;
using SmartMD.DataAccess.Service;
using SmartMD.DataModel;
using System.Windows.Forms;
using System.Xml;
using SmartMD.Manager.Utils;
using SmartMD.Manager.Container;
using Duoease.ContainerModel.Entity;
using Duoease.ContainerModel;
using Duoease.ContainerModel.Utils;
using SmartMD.DataAccess.Oracle;
using System.Data;

namespace SmartMD.Manager.Specimens
{
    /// <summary>
    /// Interaction logic for LocateSpecPanel.xaml
    /// </summary>
    public partial class LocateSpecPanel : System.Windows.Controls.UserControl
    {
        private BoxModel _box = null;
        private FridgeModel _fridge = null;
        private ShelfModel _shelf = null;
        private ContainerModelEntity cme = null;

        public LocateSpecPanel()
        {
            InitializeComponent();

            CM.fridgeClickHandler += new MouseEventHandler(OnFridgeClickHandler);
            CM.shelfClickHandler += new MouseEventHandler(OnShelfClickHandler);
            CM.MsgViewClick += new EventHandler(CM_MsgViewClick);
            CM.MsgGetOutClick += new EventHandler(CM_MsgGetOutClick);
            CM.MsgLoadClick += new EventHandler(CM_MsgLoadClick);
        }
        private ObservableCollection<ContainerEntity> _containerEntitys;

        public ObservableCollection<ContainerEntity> ContainerEntitys
        {
            get
            {
                if (_containerEntitys == null)
                {
                    if (SingletonManager.Online)
                    {
                        _containerEntitys = DataServiceManager.ContainerService.GetAllContainers();
                        for (int i = 0; i < _containerEntitys.Count; i++)
                        {
                            _containerEntitys[i].State = RecordState.Normal;
                        }
                        //SingletonManager.Cache.SaveEntity(SingletonManager.TemplatePath, "TemplateType", _templateTypes);
                    }
                    else if (SingletonManager.Cache.ExistsEntity(SingletonManager.TemplatePath, "TemplateType"))
                    {
                        //_containerEntitys = SingletonManager.Cache.LoadEntity<ObservableCollection<ContainerEntity>>(SingletonManager.ContainerPath, "ContainerEntity");
                    }
                    if (_containerEntitys == null)
                        _containerEntitys = new ObservableCollection<ContainerEntity>();
                }
                return _containerEntitys;
            }
        }
        public void OnWindowActivated()
        {
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.lbContainer.ItemsSource = ContainerEntitys;

        }

        //黄俊修改
        private void lbContainer_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            CM.FridgeModel = null;
            CM.ShelfModel = null;
            CM.BoxModel = null;
            //CM.IsShowContext = false;
            
            CM.RefreshAllLabel();

            //读取XML画模型
           XmlDocument doc = new XmlDocument();
           ContainerEntity item = (ContainerEntity)this.lbContainer.SelectedItem;


           ContainerModelEntity modelEntity = DataServiceManager.ContainerModelService.GetObjectByName(item.ModelType);
           cme = modelEntity;
            if (modelEntity != null)
            {
                doc.LoadXml(CompressionHelper.DeCompressToString(modelEntity.StyleFile));               
            }
            //装入指定的XML文档
           
            //doc.Load(System.Windows.Forms.Application.StartupPath + "\\bb.xml");
            CM.docmodel.Xml = doc;
            _fridge = CM.ParseXml(modelEntity.ModelType) as FridgeModel;
            _fridge.Name = item.SiteCode;
            CM.FridgeModel = _fridge;
            
            //冰箱梅格存放容量状态
            int column = _fridge.Column;
            int row = _fridge.Row;
            double[,] percent = new double[row, column];
            List<ContainerEntity> childcontainers =  DataServiceManager.ContainerService.GetChildContainers(item.Id);
            if (childcontainers != null)
            {
                string sitecode = null;
                for (int j = 0; j < childcontainers.Count; j++)
                {
                    sitecode = childcontainers[j].SiteCode;
                    string tmp = sitecode.Split('-')[1];
                    int columnno = int.Parse(tmp.Substring(0, 1)) - 1;
                    int rowno = int.Parse(tmp.Substring(1, 1)) - 1;
                    percent[columnno, rowno] = (double)(childcontainers[j].WholeCapacity - childcontainers[j].RemainingCapacity) / (double)childcontainers[j].WholeCapacity;              
                }
                CM.IceFullPercent = percent;
            }          
            //
            ToolStripItem mItem = new ToolStripMenuItem();
            mItem.Name = "toolStripMenuItem1";
            mItem.Size = new System.Drawing.Size(152, 22);
            mItem.Text = "添加标签信息";
            mItem.Click += new System.EventHandler(this.toolStripMenuItem1_Click);
            this.CM.contextMenu_Ice.Items.Clear();
            this.CM.contextMenu_Ice.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            mItem});
            this.CM.contextMenu_Ice.Name = "contextMS_Operate";
            this.CM.contextMenu_Ice.Size = new System.Drawing.Size(153, 48);

            lbContainer.Height = 0;
            // lbContainer.Visibility = System.Windows.Visibility.Collapsed;
            CM.Height = 500;
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            string sitecode = CM.SelectedItemID;
            var selectedItem = CM.SelectedItem;
            string strPosition = CM.BoxModel.ID + "-" + ModelUtil.GetLetter(CM.MouseRow) + CM.MouseColumn.ToString();
        }

        private void mItem_Click(object sender, EventArgs e)
        {
           System.Windows.Forms.MessageBox.Show("click");
        }
    
        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            lbContainer.Height = 500;
           // lbContainer.Visibility = System.Windows.Visibility.Visible;
            CM.Height = 0;            
        }

        #region 控件事件
        protected void OnFridgeClickHandler(object sender, MouseEventArgs e)
        {
            //测试架子第1行第2列存放容量状态
            _shelf = CM.ParseXml(ModelStyle.ShelfModel) as ShelfModel;
            if (_shelf == null)
                return;
            int column = _shelf.Column;
            int row = _shelf.Row;
            double[,] percent = new double[row, column];
            List<ContainerEntity> childcontainers = DataServiceManager.ContainerService.GetChildContainersBySitecode(_fridge.Name + CM.SelectedItemID);
            if (childcontainers != null)
            {
                string sitecode = null;
                for (int j = 0; j < childcontainers.Count; j++)
                {
                    sitecode = childcontainers[j].SiteCode;
                    string tmp = sitecode.Split('-')[2];
                    int rowno = int.Parse(tmp.Substring(0, 1)) - 1;
                    int columnno  = int.Parse(tmp.Substring(1, 1)) - 1;
                    percent[rowno, columnno] = (double)(childcontainers[j].WholeCapacity - childcontainers[j].RemainingCapacity) / (double)childcontainers[j].WholeCapacity;
                }
                CM.DrawerFullPercent = percent;
            }                 
        }

        protected void OnShelfClickHandler(object sender, MouseEventArgs e)
        {
            _box = CM.ParseXml(ModelStyle.BoxModel) as BoxModel;
            if (_box != null)
            {
                int column = _box.Column;
                int row = _box.Row;
                bool[,] isFilled = new bool[row, column];

                List<ContainerEntity> childcontainers = DataServiceManager.ContainerService.GetChildContainersBySitecode(_fridge.Name + CM.SelectedItemID);
                if (childcontainers != null)
                {
                    string sitecode = null;
                    for (int j = 0; j < childcontainers.Count; j++)
                    {
                        sitecode = childcontainers[j].SiteCode;
                        string tmp = sitecode.Split('-')[3];
                        int rowno = ModelUtil.GetNumber(tmp.Substring(0, 1)) - 1;
                        int columnno = ModelUtil.GetCodeValue(tmp.Substring(1, 1)) - 1; //int.Parse(tmp.Substring(1, 1)) - 1;
                        int per = (childcontainers[j].WholeCapacity - childcontainers[j].RemainingCapacity) / childcontainers[j].WholeCapacity;

                        isFilled[rowno, columnno] = (per == 0) ? false : true;
                    }
                    CM.BoxIsFull = isFilled;
                }
                string[,] tooltips = new string[row + 1, column + 1];
                for (int i = 1; i <= row; i++)
                {
                    for (int j = 1; j <= column; j++)
                    {
                        string sitecode = _fridge.Name + CM.SelectedItemID + "-" + ModelUtil.GetLetter(i)+ j.ToString();
                        string tip = GetTooltipsBySitecode(sitecode);
                        tooltips[i, j] = tip;
                    }
                }
                CM.BoxModel.tooltips = tooltips;
            }
        }

        protected void CM_MsgViewClick(object sender, EventArgs e)
        {
            string strPosition = CM.BoxModel.ID + "-" + ModelUtil.GetLetter(CM.MouseRow) + CM.MouseColumn.ToString();
            SpecimenMsg SM = new SpecimenMsg(SpecimenMsg.SpecimenStyle.GetMsg, CM,cme);
            if (SM.IsShow)
            {
                SM.Show();
            }
        }

        /**
         * 取出标本
         * */
        private UsingSpecDialog usingSpecDlg;
        protected void CM_MsgGetOutClick(object sender, EventArgs e)
        {
            //usingSpecDlg = new UsingSpecDialog();
            //usingSpecDlg.ShowDialog();
            string strPosition = CM.BoxModel.ID + "-" + ModelUtil.GetLetter(CM.MouseRow) + CM.MouseColumn.ToString();
            SpecimenMsg SM = new SpecimenMsg(SpecimenMsg.SpecimenStyle.RemoveMsg, CM,cme);
            if (SM.IsShow)
            {
                SM.Show();
            }           
        }

        protected void CM_MsgLoadClick(object sender, EventArgs e)
        {
            string strPosition = CM.BoxModel.ID + "-" + ModelUtil.GetLetter(CM.MouseRow) + CM.MouseColumn.ToString();
            SpecimenMsg SM = new SpecimenMsg(SpecimenMsg.SpecimenStyle.InputMsg, CM,cme);
            SM.Show();
            //System.Windows.MessageBox.Show("打开载入标本窗口,行列号：" + CM.MouseRow + "," + CM.MouseColumn, "提示");
        }
        #endregion

        private string GetTooltipsBySitecode(string sitecode)
        {
            StringBuilder tooltip = new StringBuilder();
            StringBuilder sb = new StringBuilder();
            sb.Append("select t3.entityid, t.collecttime, t.collecter, t3.sitecode, t3.customcode, t.specification, t.spectype, t2.name as patientname, t2.sex, t2.birthday, t2.followupno, t2.hospitalno, t2.pathologyno");
            sb.Append(" from duo_specimens t, duo_patient t2, duo_spec_entity t3 ");
            sb.Append("  where t.patientid = t2.patientid and t.specid = t3.specid");
            sb.Append(" and sitecode = '" + sitecode + "'");

            DataTable dt = ConnectDatabase.getInstance().Select(sb.ToString());
            if (dt != null)
            {
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    TooltipInfo tooltipInfo = new TooltipInfo();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string clmName;
                        clmName = dt.Columns[i].ColumnName;
                        tooltipInfo.setValue(clmName, dt.Rows[j][clmName]);
                    }
                    tooltip.Append("位置编码：" + tooltipInfo.Sitecode + "");
                    tooltip.Append("\n标本编码/自定义编码：" + tooltipInfo.Id + "/" + tooltipInfo.CustomCode);
                    tooltip.Append("\n标本类型/规格：" + tooltipInfo.SpecType + "(" + tooltipInfo.Specification + ")");
                    tooltip.Append("\n姓名（性别/年龄）：" + tooltipInfo.Name + "(" + tooltipInfo.Sex + "/" + tooltipInfo.Age + ")");
                    tooltip.Append("\n随访时间（周次）：" + tooltipInfo.FollowUpDate + "(第" + tooltipInfo.FollowUpTimes + "周)");
                    tooltip.Append("\n随访号/随访人：" + tooltipInfo.FollowUpNo + "/" + tooltipInfo.FollowUper );
                    tooltip.Append("\n住院号/病理号：" + tooltipInfo.HostpitalNo + "/" + tooltipInfo.PathologyNo);          
                }
                return tooltip.ToString();
            }
            else
                return "";          
        }
    }
}
